/**
* Copyright (c) 2016-2100 yunclouds
*/
package com.yunqian.redot.service;

import com.yunqian.exception.ServiceException;
import com.yunqian.redot.constant.BooleanStatus;
import com.yunqian.redot.constant.Operation;
import com.yunqian.redot.constant.OperationMenus;
import com.yunqian.redot.constant.TicketType;
import com.yunqian.redot.domain.Ticket;
import com.yunqian.redot.repository.TicketOrderRepository;
import com.yunqian.redot.repository.TicketRepository;
import com.yunqian.service.BaseService;
import com.yunqian.util.validate.Validator;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * 门票管理
 *
 * @author zsy
 * 2018-09-29 15:55:11
 */
@Service
@Log4j2
public class TicketService extends BaseService<Ticket, Long> {

    @Autowired
    private TicketRepository ticketRepository;
    @Autowired
    private OperationLogService operationLogService;
    @Autowired
    private TicketOrderRepository ticketOrderRepository;

    public Ticket save(Ticket ticket, Long userId) {
        Boolean exist = ticketRepository.existsByTitle(ticket.getTitle());
        if(exist){
            throw new ServiceException("添加失败，该门票已存在。");
        }
        super.save(ticket);
        if(Validator.isNull(ticket.getRelateTicketArr())){
            ticket.setRelateTicketArr("[" + ticket.getId() + "]");
        }
        if(ticket.getType() == 1){
            operationLogService.save(OperationMenus.DEFAULT_TICKET, Operation.ADD, userId);
        }else {
            operationLogService.save(OperationMenus.PACKAGES_TICKETS, Operation.ADD, userId);
        }
        return ticket;
    }

    public Ticket update(Long id, Map<String, Object> map, Long userId) {
        String title = (String) map.get("title");
        if(Validator.isNotNull(title)){
            Boolean exist = ticketRepository.existsByTitleAndIdNot(title, id);
            if(exist){
                throw new ServiceException("修改失败，该门票已存在。");
            }
        }
        Ticket ticket = super.update(id, map);
        if(ticket.getType() == 1){
            operationLogService.save(OperationMenus.DEFAULT_TICKET, Operation.UPDATE, userId);
        }else {
            operationLogService.save(OperationMenus.PACKAGES_TICKETS, Operation.UPDATE, userId);
        }
        return ticket;
    }

    public List<Ticket> list(Integer type){
        return ticketRepository.findAllByTypeOrderByIdAsc(type);
    }

    public List<Ticket> findAllByStatus(){
        return ticketRepository.findAllByStatus(BooleanStatus.YES.getCode());
    }

    public List<Ticket> findAllByType(){
        return ticketRepository.findAllByType(1);
    }

    public String toName(String relateTicketArr){

        // 获取基础票列表
        List<Ticket> ticketList = this.list(TicketType.BASE_TICKET.getCode());

        StringBuilder sb = new StringBuilder();
        String[] arr = relateTicketArr.substring(1,relateTicketArr.length() - 1).split(",");
        for(int i=0; i< arr.length;i++){
            for(Ticket ticket: ticketList){
                if(arr[i].equals(String.valueOf(ticket.getId()))){
                    if(i != arr.length -1){
                        sb.append(ticket.getTitle() + ",");
                    }else{
                        sb.append(ticket.getTitle());
                    }
                }
            }
        }
        return sb.toString();
    }

    public Ticket getFirstByRelateTicketArr(String str){
        return ticketRepository.findFirstByRelateTicketArr(str);
    }

    public void subtractStock(Long id, Integer quantity){
        ticketRepository.subtractStock(id, quantity);
    }

    public void addStock(){
        List<Map<String,Object>> map = ticketOrderRepository.findAllByOrderStatus();
        map.forEach(item -> {
            ticketRepository.addStock(Long.valueOf(item.get("ticketId").toString()), Integer.valueOf(item.get("quantity").toString()));
        });
    }

    public boolean existsByTypeAndStatusAndId(Long id){
        return ticketRepository.existsByTypeAndStatusAndId(TicketType.BASE_TICKET.getCode(), BooleanStatus.YES.getCode(),id);
    }
}
